﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Net;
using Microsoft.Office.Interop.Word;

public partial class Pages_BillDetails : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Session != null && Session["dsBillDetails"] != null)
            {
                DataSet dsReport = new DataSet();
                dsReport = (DataSet)Session["dsBillDetails"];
                CallDisplayReport(dsReport);
                //  CreateBill();
            }
            else
            {

            }
        }
    }

    private void CallDisplayReport(DataSet dsContent)
    {
        if (dsContent.Tables[0].Rows.Count > 0)
        {
            imgLogo.ImageUrl = ImageURL(dsContent.Tables[0].Rows[0]["CTID"].ToString(), "C", 1);
            lblSuppCompName.Text = dsContent.Tables[0].Rows[0]["TransportCompany"].ToString();
            lblAddress.Text = dsContent.Tables[0].Rows[0]["CTAddress"].ToString();
            lblEmail.Text = dsContent.Tables[0].Rows[0]["CTEmail"].ToString();
            MailId.HRef = "mailto:" + dsContent.Tables[0].Rows[0]["CTEmail"].ToString();
            lblMobileNo.Text = dsContent.Tables[0].Rows[0]["CTPhone"].ToString();
           // lblDate.Text = DateTime.Now.ToShortDateString();
            lblCCComp.Text = dsContent.Tables[0].Rows[0]["ContractorCompany"].ToString();
            lblCCCompName.Text = dsContent.Tables[0].Rows[0]["TransportCompany"].ToString();
            lblCCCompAdd.Text = dsContent.Tables[0].Rows[0]["CCAddress"].ToString();
            CCVATNo.Text = dsContent.Tables[0].Rows[0]["CCVVAT"].ToString();
            lblCTTIN.Text = dsContent.Tables[0].Rows[0]["CTVAT"].ToString();

            // Session["Rate"] = "22";
            decimal cft = 0;
            decimal rate = 0;
            double amount = 0;
            double vatAmount = 0;
            double totAmount = 0;
            //if (Session["Rate"] != null)
            //{
            //    rate = Convert.ToDecimal(Session["Rate"].ToString());
            //}
            //else
            //{
            rate = Convert.ToDecimal(dsContent.Tables[2].Rows[0]["Rate"].ToString());
            lblDate.Text = dsContent.Tables[2].Rows[0]["BillDate"].ToString();
            //}
            cft = Convert.ToDecimal(dsContent.Tables[0].Rows[0]["Quantity"].ToString());
            amount = (double)(cft * rate);
            vatAmount = amount * .05;
            totAmount = amount + vatAmount;
            lblMaterial.Text = dsContent.Tables[0].Rows[0]["Material"].ToString();
            lblQuantity.Text = cft.ToString() + " MT";
            lblRate.Text = rate.ToString();
            lblAmount.Text = amount.ToString();
            lblVat.Text = vatAmount.ToString();
            lblTotalAmount.Text = totAmount.ToString();
            lblAmountInWords.Text = DataAccessClass.translateWholeNumber(((int)totAmount).ToString());
            lblCCCompStat.Text = dsContent.Tables[0].Rows[0]["ContractorCompany"].ToString();
            lblBillNo.Text = dsContent.Tables[2].Rows[0]["BillNo"].ToString();
            // Generate rows and cells.
            int numrows = Convert.ToInt32(dsContent.Tables[1].Rows.Count);
            int numcells = Convert.ToInt32(6);

            for (int j = 0; j < numrows; j++)
            {
                HtmlTableRow r = new HtmlTableRow();
                r.BgColor = "Gainsboro";
                for (int i = 0; i < numcells; i++)
                {
                    HtmlTableCell c = new HtmlTableCell();
                    c.Controls.Add(new LiteralControl(dsContent.Tables[1].Rows[j][i].ToString()));
                    r.Cells.Add(c);
                }
                tblDetails.Rows.Add(r);
            }
            HtmlTableRow rTotal = new HtmlTableRow();
            HtmlTableCell cl;
            cl = new HtmlTableCell();
            cl.Align = "left";
            cl.Controls.Add(new LiteralControl("Total"));
            rTotal.Cells.Add(cl);
            cl = new HtmlTableCell();
            cl.Controls.Add(new LiteralControl(""));
            rTotal.Cells.Add(cl);
            cl = new HtmlTableCell();
            cl.Controls.Add(new LiteralControl(""));
            rTotal.Cells.Add(cl);
            cl = new HtmlTableCell();
            cl.Controls.Add(new LiteralControl(""));
            rTotal.Cells.Add(cl);
            cl = new HtmlTableCell();
            cl.Controls.Add(new LiteralControl(""));
            rTotal.Cells.Add(cl);
            cl = new HtmlTableCell();
            cl.Align = "center";
            cl.Controls.Add(new LiteralControl(cft.ToString() + " MT"));
            rTotal.Cells.Add(cl);
            tblDetails.Rows.Add(rTotal);
        }
    }
    public string ImageURL(string img_id, string type, int imgNo)
    {
        return ("GetImage.aspx?id=" + img_id + "&Type=" + type + "&ImageNo=" + imgNo);
    }
    protected void btnGenerate_Click(object sender, EventArgs e)
    {
        CreateBill("E");
    }
    protected void btnGenerateWord_Click(object sender, EventArgs e)
    {
      //  CreateBill("W");
       // ExportToWord();
        DataSet ds = new DataSet();
        ds = (DataSet)Session["dsBillDetails"];
        CreateWordFile(ds);
    }

    private void ExportToWord()
    {
        string url = Request.Url.OriginalString;
        //Prepare the web page we will be asking for
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "application/msword";
        request.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0";
        //Execute the request
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        //We will read data via the response stream
        Stream resStream = response.GetResponseStream();
        //Write content into the MemoryStream
        BinaryReader resReader = new BinaryReader(resStream);
        MemoryStream docStream = new MemoryStream(resReader.ReadBytes((int)response.ContentLength));
        //Create document
        //Document doc = new Document(docStream);
        //Save document
        //doc.Save(@"Test138\out.doc");
    }
    private void CreateBill(string type)
    {

        Response.Clear(); //this clears the Response of any headers or previous output 
        Response.Buffer = true; //make sure that the entire output is rendered simultaneously
        ///
        ///Set content type to MS Excel sheet
        ///Use "application/msword" for MS Word doc files
        ///"application/pdf" for PDF files
        ///
        if (type=="E")
        {
            Response.ContentType = "application/vnd.ms-excel";
        }
        else if (type=="W")
        {
           Response.ContentType = "application/msword";  
        }
       
        StringWriter stringWriter = new StringWriter(); //System.IO namespace should be used
        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
        ///
        ///Render the entire Page control in the HtmlTextWriter object
        ///We can render individual controls also, like a DataGrid to be
        ///exported in custom format (excel, word etc)
        ///
        this.panMain.RenderControl(htmlTextWriter);
       // RenderControl(htmlTextWriter);
        Response.Write(stringWriter.ToString());
        Response.End();
    }

    public void CreateWordFile(DataSet dsContent)
    {
        object oMissing = System.Reflection.Missing.Value;
        object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark  */

        //Start Word and create a new document.
        Microsoft.Office.Interop.Word._Application oWord;
        Microsoft.Office.Interop.Word._Document oDoc;
        oWord = new Microsoft.Office.Interop.Word.Application();
        oWord.Visible = true;
        oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
            ref oMissing, ref oMissing);
        //oDoc.InlineShapes.AddHorizontalLine("", ref oMissing);
        /// oDoc.InlineShapes.AddPicture(ImageURL(dsContent.Tables[0].Rows[0]["CTID"].ToString(), "C", 1), ref oMissing, ref oMissing, ref oMissing);
        //Insert a paragraph at the beginning of the document.
        Microsoft.Office.Interop.Word.Paragraph oPara1;
        oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
        oPara1.Format.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
        oPara1.Range.Text = dsContent.Tables[0].Rows[0]["TransportCompany"].ToString();
        oPara1.Range.Font.Bold = 1;
        oPara1.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
        oPara1.Format.SpaceAfter = 1;    //24 pt spacing after paragraph.
        oPara1.Range.InsertParagraphAfter();

        //Insert a paragraph at the end of the document.
        Microsoft.Office.Interop.Word.Paragraph oPara2;
        object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
        oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);
        oPara2.Range.Text = dsContent.Tables[0].Rows[0]["CTAddress"].ToString();
        oPara2.Format.SpaceAfter = 1;
        oPara2.Range.InsertParagraphAfter();

        //Insert another paragraph.
        Microsoft.Office.Interop.Word.Paragraph oPara3;
        oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
        oPara3 = oDoc.Content.Paragraphs.Add(ref oRng);
        oPara3.Range.Text = "Mobile :" + dsContent.Tables[0].Rows[0]["CTPhone"].ToString();
        oPara3.Range.Font.Bold = 0;
        oPara3.Format.SpaceAfter = 1;
        oPara3.Range.InsertParagraphAfter();

        //Insert another paragraph.
        Microsoft.Office.Interop.Word.Paragraph oPara14;
        oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
        oPara14 = oDoc.Content.Paragraphs.Add(ref oRng);
        oPara14.Range.Text = "Email :" + dsContent.Tables[0].Rows[0]["CTEmail"].ToString();
        oPara14.Range.Font.Bold = 0;
        oPara14.Format.SpaceAfter = 24;
        oPara14.Range.InsertParagraphAfter();

        //Insert a 3 x 5 table, fill it with data, and make the first row
        //bold and italic.
        Microsoft.Office.Interop.Word.Table oTable;
        Microsoft.Office.Interop.Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
        oTable = oDoc.Tables.Add(wrdRng, 2, 4, ref oMissing, ref oMissing);
        oTable.Range.ParagraphFormat.SpaceAfter = 6;


        oTable.Cell(1, 1).Range.Text = "Material";
        oTable.Cell(1, 2).Range.Text = "Quantity";
        oTable.Cell(1, 3).Range.Text = "Rate";
        oTable.Cell(1, 4).Range.Text = "Amount";
        oTable.Cell(2, 1).Range.Text = dsContent.Tables[1].Rows[0]["Material"].ToString();
        oTable.Cell(2, 2).Range.Text = dsContent.Tables[1].Rows[0]["Quantity"].ToString();
        oTable.Cell(2, 3).Range.Text = "23";
        oTable.Cell(2, 4).Range.Text = "230";
        oTable.Rows[1].Range.Font.Bold = 1;
        oTable.Rows[1].Range.Font.Italic = 1;


        string comment = "";
        comment = "I / Whereby certify that my/our registration certificate under the Maharashtra Value Added Tax " +
                 " Act, 2002 is in force on the date on which the sale of goods specified in this tax invoice is made " +
                  "by me/us and that the transaction of sale covered by this invoice has been effected by me/us and " +
                  "it shall be accouted for in the turnover of sales while filling of return and the due tax , if any, if " +
                 " any, payable on the sale has been paid or shall be paid";
        object oPos;
        double dPos = oWord.InchesToPoints(7);
        oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();
        //  do
        //  {
        wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
        wrdRng.ParagraphFormat.SpaceAfter = 6;
        wrdRng.InsertAfter(comment);
        wrdRng.InsertParagraphAfter();
        oPos = wrdRng.get_Information
                       (Microsoft.Office.Interop.Word.WdInformation.wdVerticalPositionRelativeToPage);
        // }
        // while (dPos >= Convert.ToDouble(oPos));

        object oCollapseEnd = Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd;
        object oPageBreak = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;
        wrdRng.Collapse(ref oCollapseEnd);
        wrdRng.InsertBreak(ref oPageBreak);
        wrdRng.Collapse(ref oCollapseEnd);
        //  wrdRng.InsertAfter("We're now on page 2. Here's my chart:");
        wrdRng.InsertParagraphAfter();


        //Add text after the chart.
        wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
        wrdRng.InsertParagraphAfter();
        wrdRng.InsertAfter("THE END.");

        //Close this form.
        // this.Close();

    }
}